package com.my.all.controller;

import com.my.all.pojo.Goods;
import com.my.all.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//将Controller注解标记的类自动注册到SpringIoc容器中，由spring管理该类对象的生存周期
@Controller
@RequestMapping(value = "/goods")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    //当向前端返回数据时，需要用到ResponseBody注解
    //主要做两件事：1、将返回值转换成JSON，
    // 如果返回值是String或者其他基本数据类型则不满足key-value形式，不能转换成json类型，则返回字符串
    @ResponseBody
    @RequestMapping(value = "/insertGoods",method = RequestMethod.GET)
    public String insertGoods(@RequestParam("goodsName") String goodsName, @RequestParam("goodsCount") String goodsCount,
                           @RequestParam("goodsPrice") String goodsPrice, @RequestParam("goodsInfo") String goodsInfo){
        int result = goodsService.insertGoods(goodsName,goodsCount,goodsPrice,goodsInfo);
          if(result == 1){
              return "添加成功";
          }
          return "添加失败";
    }

    @ResponseBody
    @RequestMapping(value = "/deleteGoodsById",method = RequestMethod.GET)
    public String deleteGoodsById(@RequestParam("goodsId") String goodsId){
        if (goodsService.deleteGoodsById(Long.parseLong(goodsId)) == 1){
            return "删除成功";
        }
        return "删除失败";
    }

    @ResponseBody
    @RequestMapping(value = "/selectAll",method = RequestMethod.GET)
    public List<Goods> selectAll(){
        return goodsService.selectAll();
    }

    @ResponseBody
    @RequestMapping(value = "/updateGoods",method = RequestMethod.GET)
    public String  updateGoods(@RequestParam("goodsId") String goodsId,  @RequestParam("goodsCount") String goodsCount,
                           @RequestParam("goodsPrice") String goodsPrice, @RequestParam("goodsInfo") String goodsInfo){

        Goods goods = goodsService.updateGoods(goodsId, goodsCount, goodsPrice, goodsInfo);
        if (goods == null){
            return "更新失败，（输入Id可能不存在）";
        }
        return "更新成功";
    }

    @ResponseBody
    @RequestMapping(value = "/selectGoodsById",method = RequestMethod.GET)
    public Goods selectGoodsById(@RequestParam("goodsId") String goodsId){

        Goods goods = goodsService.selectGoodsById(goodsId);
        if (goods == null){
            System.out.println("查看失败，（输入Id可能不存在）");
            return null;
        }
        return goods;
    }

    @ResponseBody
    @GetMapping("/index")
    public String index(){
        return "/goods/html/index";
    }
}

